import datetime
import json

from django.conf import settings
from django.contrib.auth.models import Permission, Group
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.utils import model_meta
from rest_framework.viewsets import ModelViewSet
from apps.users.models import User
from apps.meiduo_admin.serializers.permission_serializers import PermissionSerialzier, GroupSerialzier, AdminSerialzier, \
    GroupSimpleSerializers
from apps.meiduo_admin.utils.pagenum import PageNum


# 权限管理
class PermissionView(ListAPIView):
    serializer_class = PermissionSerialzier
    # 没有子集则为第三级分类  自关联有两个属性 parent为父属性  subs为子属性
    queryset = Permission.objects.all()
    pagination_class = PageNum


# 用户组管理
class GroupsView(ModelViewSet):
    serializer_class = GroupSerialzier
    queryset = Group.objects.all()
    pagination_class = PageNum
    # 查询所有权限
    def simple(self, reqeust):
        pers = Permission.objects.all()
        ser = PermissionSerialzier(pers, many=True)
        return Response(ser.data)


# 管理员管理
class AdminView(ModelViewSet):
    serializer_class = AdminSerialzier
    queryset = User.objects.filter(is_staff=True)
    pagination_class = PageNum
    def simple(self,request):
        pers = Group.objects.all()
        ser = GroupSerialzier(pers, many=True)
        return Response(ser.data)

class GroupSimpleView(ListAPIView):
    serializer_class = GroupSimpleSerializers
    queryset = Group.objects.all()


from django.views import View
from django.http import JsonResponse
import jwt

# 自定义django的jwt登录验证

class LoginView(View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        username = json_dict.get("username")
        password = json_dict.get("password")
        if not all([username,password]):
            return JsonResponse({"msg":"数据不完整"},status=400)
        try:
            user = User.objects.get(username=username,is_staff=True)
        except:
            return JsonResponse({"msg": "用户名无效"}, status=400)
        if not user.check_password(password):
            return JsonResponse({"msg": "密码无效"}, status=400)
        payload = {
                 "id":user.id,
                "username": user.username,
                "exp":datetime.datetime.utcnow()+datetime.timedelta(days=14)
        }
        token = jwt.encode(payload,settings.SECRET_KEY).decode()
        return JsonResponse({
                "user_id":user.id,
                "username": user.username,
                "token":token
        })
